import _ from 'lodash';
import { Request, Response, NextFunction } from 'express';
import { getComment, createComment, deleteComment, getIdComment, setLikeComments, getComment_likes, deleteLikeComments, updateComment, getUserLikeComments } from './comment.service';
import axios from 'axios';
import { getFourBoroughs, getIdTutor, getThreeBoroughs, getTwoBoroughs } from '../tutor/tutor.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let book_id = request.query.book_id
  let pageNo = request.query.pageNo
  let pageSize = request.query.pageSize
  let status = request.query.status

  const data = await getComment(parseInt(`${book_id}`, 10), parseInt(`${pageNo}`, 10), parseInt(`${pageSize}`, 10), parseInt(`${status}`, 10));

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const commentDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdComment(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let commentModel = request.body;

  delete commentModel.total;
  delete commentModel.user_info;
  delete commentModel.kitapName;
  let releaseTime = Math.floor(new Date().getTime())
  commentModel.releaseTime = releaseTime;

  let ip = request.headers['x-real-ip'];
  // 高德地图 IP 定位 API
  const apiKey = '70205e32cd969c90d3a32115185869c4';
  const url = `https://restapi.amap.com/v3/ip?ip=${ip}&output=JSON&key=${apiKey}`;
  const map = await axios.get(url);
  const adcode = map.data?.adcode;
  let boroughs_name_ug = '';

  if (adcode.length > 0 && adcode > 0) {

    if (!adcode.startsWith('65')) {
      // 内地
      const firstTwo = adcode.substring(0, 2);
      let boroughs = await getTwoBoroughs(firstTwo);
      boroughs_name_ug = boroughs[0].name_ug

    } else if (adcode.startsWith('659')) {
      // 新疆兵团
      let boroughs = await getThreeBoroughs(adcode);
      boroughs_name_ug = boroughs[0].name_ug;

    } else {
      // 新疆各市
      const firstFour = adcode.substring(0, 4);
      let boroughs = await getFourBoroughs(firstFour);
      boroughs_name_ug = boroughs[0].name_ug;

    }

    commentModel.boroughs_name_zh = map.data.city; // 添加行政区名称 zh
    commentModel.adcode = adcode; // 添加行政区代码
    commentModel.boroughs_name_ug = boroughs_name_ug; // 添加行政区名称 ug

  }
  
  commentModel.user_ip = ip; // 添加用户 IP
  
  // 创建内容
  try {
    if(!commentModel.id) {
      await createComment(commentModel);

      return response.send({msg: '创建成功 ~', status: 200});
    } else {
      await updateComment(commentModel, commentModel.id);

      return response.send({ msg: '更新成功 ~', status: 200 });
    }

    
  } catch (error) {
    next(error);
  }
}

/**
 * 状态管理
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let commentModel = request.body;

  interface CommentModel {
    id?: number;
    status: number;
  }

  let post: Partial<CommentModel> = { status: commentModel.status };

  // 创建内容
  try {
    await updateComment(post, commentModel.id);

    return response.send({ msg: '修改状态成功 ~', status: 200 });
  } catch (error) {
    next(error);
  }
}

/**
 * 点赞评论
 */
export const likeComments = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { comment_id, user_id } = request.body;

  try {

    // 获取用户点赞评论
    let CommentLike = await getComment_likes(comment_id, user_id);
    
    // 获取评论
    let commentCount = await getIdComment(comment_id);

    // 类型守卫：确保是数组再访问 length
    if (Array.isArray(CommentLike)) {
      if (CommentLike.length === 0) {
        let commentPost = request.body;
        let created_at = Date.now(); // 当前时间戳
        commentPost.created_at = created_at; // 添加创建时间
        await setLikeComments(commentPost); // 创建用户点赞评论
        
        let commentLikePlus = (commentCount as any)[0].like_count + 1;
        let post = { like_count: commentLikePlus }
        await updateCommentLike(post, comment_id); // 更新评论点赞数

        return response.send('评论点赞成功 ~');
      } else {
        await deleteLikeComments((CommentLike as any)[0].id); // 删除评论点赞

        let commentLikePlus = (commentCount as any)[0].like_count > 0 ? (commentCount as any)[0].like_count - 1 : 0;
        let post = { like_count: commentLikePlus }
        await updateCommentLike(post, comment_id); // 更新评论点赞数

        return response.send('删除成功 ~');

      }
    }
  
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;
  let post = { status: 2 }

  // 删除内容
  try {
    const data = await deleteComment(post, parseInt(postId, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
};

// 更新评论（更新评论点赞）
const updateCommentLike = async (post: any, postId: number) => {
  return await updateComment(post, postId)
};

/**
 * 获取用户点赞评论
 */
export const userLikeComment = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const { user_id } = request.body;

  // 获取用户点赞评论
  try {
    const data = await getUserLikeComments(parseInt(user_id, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
}
